﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.Entity;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Data.SqlClient;

using System.Reflection;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;

namespace UCWebpart.Admin
{
    public partial class mtrUserControl : System.Web.UI.UserControl
    {
        UserInfo userInfo;
        int uLevel = 0;
        List<MTR_Admin> AdminInfoList;
        protected void Page_Load(object sender, EventArgs e)
        {
            Label3.Text = "";
            if (Session["userInfo"] == null)
            {
                Response.Redirect("../Login.aspx", false);
                return;
            }
            userInfo = (UserInfo)Session["userInfo"];
            AdminInfoList = userInfo.AdminInfoList;
            List<string> company = new List<string>();
            foreach (MTR_Admin ma in AdminInfoList)
            {
                uLevel = uLevel > Convert.ToInt32(ma.adminLevel) ? uLevel : Convert.ToInt32(ma.adminLevel);
                //company.Add(ma.OrgType1);
            }
            string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;
            if (uLevel < 2)//普通管理员
            {
                //Label3.Text = "<script>alert('您没有权限查看当前页面！'); </script>";
                Response.Write("<script>alert('您没有权限查看当前页面！'); </script>");
                Response.Write("<script language=javascript>history.go(-2);</script>");
            }
            if (uLevel == 2)//高级管理员
            {
                if (!this.IsPostBack)
                {

                    string strSQL = "SELECT distinct [Type],[id] FROM [VenueBooking].[dbo].[MTR_bas_Type] where [available] =1 order by id ";
                    venueType.DataSource = Worker.GetDataSet(strSQL, conn);
                    venueType.DataTextField = "Type";
                    venueType.DataValueField = "Type";
                    venueType.DataBind();
                }
            }
            if (uLevel >= 3)
            {
                adminLevel.Enabled = true;
                if (!this.IsPostBack)
                {
                    string strSQL1 = "SELECT distinct [Type],[id] FROM [VenueBooking].[dbo].[MTR_bas_Type] where [available] =1 order by id";
                    venueType.DataSource = Worker.GetDataSet(strSQL1, conn);
                    venueType.DataTextField = "Type";
                    venueType.DataValueField = "Type";
                    venueType.DataBind();
                }
            }
            if (!this.IsPostBack)
            {
                string strSQL2 = "SELECT distinct [adminName] FROM [VenueBooking].[dbo].[MTR_bas_Admin] where Available = 1 and adminLevel = 1";
                normalManage.DataSource = Worker.GetDataSet(strSQL2, conn);
                normalManage.DataTextField = "adminName";
                normalManage.DataValueField = "adminName";
                normalManage.DataBind();

                string strSQL3 = string.Format(@"SELECT [mtrName] as '名称',[type] as '类型',[mtrCompanyRuc] + ' '+[mtrDeptRuc] as '可用部门'
                ,[mtrAddress]+[mtrAddress1] as '地址' ,[mtrCapacity] as '容量',[mtrPhone] as '电话',[mtrType] as '级别'
                FROM [VenueBooking].[dbo].[MTR_bas_Meetingroom] where mtrDelete = 1 and undefine3 = '{0}'", normalManage.SelectedItem.Text);
                GridView2.DataSource = Worker.GetDataSet(strSQL3, conn).Tables[0];
                GridView2.DataBind();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        public int CheckUserName(string userName)
        {
            string cString = WebConfigurationManager.ConnectionStrings["WorkFlowConnectionString"].ConnectionString;
            string strSQL = string.Format(@"select 1 from [WorkFlow].[dbo].[RUC_Users] where SamAccountName='{0}' and IfDelete=0", userName);
            DataTable dt = Worker.GetDataSet(strSQL, cString).Tables[0];
            return dt.Rows.Count;
        }

        protected void Button1_Click1(object sender, EventArgs e)
        {
            try
            {
                string aName = AdminName.Text;
                int aLevel = Convert.ToInt32(adminLevel.SelectedValue);
                
                if (CheckUserName(aName)<1) {
                    Label3.Text = "<script>alert('您输入的管理员不存在！'); </script>";
                    return;
                }
                using (meetingroomManagementEntities useAdd = new meetingroomManagementEntities())
                {
                    //创建管理员实体
                    MTR_bas_Admin add = new MTR_bas_Admin();
                    add.adminName = aName;
                    add.VenueType = venueType.SelectedItem.Text;
                    add.adminLevel = aLevel;
                    add.Available = true;
                    useAdd.MTR_bas_Admin.Add(add);
                    //写入数据库，完成增加操作
                    useAdd.SaveChanges();
                    Label3.Text = "<script>alert('管理员添加成功！'); </script>";
                    Label3.Text = "<script window.location.href='UserManage.aspx'</script>";
                    //Response.Write("<script>alert('管理员添加成功！'); </script>");
                    //Response.Redirect("UserManage.aspx", false);
                }
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, "添加管理员");
                Response.Write("<script>alert('" + ex.Message + "'); </script>");
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if ((DropDownList)e.Row.FindControl("ddlVenueType") != null)
            {
                if (uLevel == 3)
                {
                    //绑定类型
                    DropDownList DDlType = (DropDownList)e.Row.FindControl("ddlVenueType");
                    string conn1 = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;//"Data Source=mesdbsrv.gwkf.cn;Initial Catalog=VenueBooking;User ID=vbuser;Password=vb_2013";
                    string strSQL2 = "SELECT distinct [Type],[id] FROM [VenueBooking].[dbo].[MTR_bas_Type] where [available] =1 order by id";
                    DDlType.DataSource = Worker.GetDataSet(strSQL2, conn1); ;
                    DDlType.DataTextField = "Type";
                    DDlType.DataValueField = "Type";
                    DDlType.DataBind();
                    TextBox TBType = (TextBox)e.Row.FindControl("tbType");
                    for (int i = 0; i < DDlType.Items.Count; i++)
                    {
                        if (TBType.Text == DDlType.Items[i].Text)
                        {
                            DDlType.Items[i].Selected = true;
                        }
                    }

                    TextBox TBlevel = (TextBox)e.Row.FindControl("TBlevel");
                    DropDownList DDllevel = (DropDownList)e.Row.FindControl("DDLlevel");
                    for (int i = 0; i < DDllevel.Items.Count; i++)
                    {
                        if (TBlevel.Text == DDllevel.Items[i].Value)
                        {
                            DDllevel.Items[i].Selected = true;
                        }
                    }
                }
                if (uLevel == 2)
                {
                    //绑定类型
                    DropDownList DDlType = (DropDownList)e.Row.FindControl("ddlVenueType");
                    string conn1 = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;//"Data Source=mesdbsrv.gwkf.cn;Initial Catalog=VenueBooking;User ID=vbuser;Password=vb_2013";
                    string strSQL2 = "SELECT distinct [Type],[id] FROM [VenueBooking].[dbo].[MTR_bas_Type] where [available] =1 order by id";
                    DDlType.DataSource = Worker.GetDataSet(strSQL2, conn1); ;
                    DDlType.DataTextField = "Type";
                    DDlType.DataValueField = "Type";
                    DDlType.DataBind();
                    TextBox TBType = (TextBox)e.Row.FindControl("tbType");
                    for (int i = 0; i < DDlType.Items.Count; i++)
                    {
                        if (TBType.Text == DDlType.Items[i].Text)
                        {
                            DDlType.Items[i].Selected = true;
                        }
                    }
                    TextBox TBlevel = (TextBox)e.Row.FindControl("TBlevel");
                    DropDownList DDllevel = (DropDownList)e.Row.FindControl("DDLlevel");
                    for (int i = 0; i < DDllevel.Items.Count; i++)
                    {
                        if (TBlevel.Text == DDllevel.Items[i].Value)
                        {
                            DDllevel.Items[i].Selected = true;
                        }
                    }
                }
            }
        }
        protected void ddlVenueType_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList venueType = sender as DropDownList;
            GridViewRow gvr = (GridViewRow)venueType.NamingContainer;
            TextBox type = gvr.FindControl("tbType") as TextBox;
            type.Text = venueType.SelectedItem.Text;
        }
       
        /// <summary>
        /// 执行删除之前的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //取到主键
            int id = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value);
            MTR_bas_Admin mba = new MTR_bas_Admin();
            if (uLevel == 2)//判断是否可删
            {
                using (var mtr_resEn = new meetingroomManagementEntities())
                {
                    var cls = (from c in mtr_resEn.MTR_bas_Admin
                               where c.Available && c.adminId == id
                               select c).SingleOrDefault<MTR_bas_Admin>();
                    if (cls.adminLevel == 2)
                    {
                        e.Cancel = true;
                        Label3.Text = "<script>alert('您当前的权限不能删除高级管理员！'); </script>";
                        //Response.Redirect("UserManage.aspx", false);
                        return;
                    }
                }
            }
            using (var mtr_resEn = new meetingroomManagementEntities())
            {
                var adm = (from m in mtr_resEn.MTR_bas_Meetingroom
                           join
                               a in mtr_resEn.MTR_bas_Admin on m.undefine3 equals a.adminName
                           where a.adminId == id && m.mtrDelete && a.adminLevel == 1
                           select new
                           {
                               mtrId = m.mtrId,
                               mtrName = m.mtrName,
                               mtrType = m.mtrType
                           }).ToList();
                if (adm.Count > 0)
                {
                    e.Cancel = true;
                    Label3.Text = "<script>alert('当前管理员管理" + adm.Count + "个场地，请先更改场地配置再删除');</script>";

                    return;
                }
            }
            Response.Redirect("UserManage.aspx", false);
        }

        protected void DDLlevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList venueType = sender as DropDownList;
            GridViewRow gvr = (GridViewRow)venueType.NamingContainer;
            TextBox type = gvr.FindControl("TBlevel") as TextBox;
            type.Text = venueType.SelectedItem.Value;
        }

        protected void normalManage_SelectedIndexChanged(object sender, EventArgs e)
        {
            string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;
            string strSQL3 = string.Format(@"SELECT [mtrName] as '名称',[type] as '类型',[mtrCompanyRuc] + ' '+[mtrDeptRuc] as '可用部门'
                ,[mtrAddress]+[mtrAddress1] as '地址' ,[mtrCapacity] as '容量',[mtrPhone] as '电话',[mtrType] as '级别'
                FROM [VenueBooking].[dbo].[MTR_bas_Meetingroom] where mtrDelete = 1 and undefine3 = '{0}'", normalManage.SelectedItem.Text);
            GridView2.DataSource = Worker.GetDataSet(strSQL3, conn).Tables[0];
            GridView2.DataBind();
        }

        #region
//        protected List<string> getDeptByNameComLevel(string userName, string Company, int Level) 
//        {
//            string com = Company;
//            List<string> dept = new List<string>();
//            if (Level == 2)//高级管理员
//            {
//                foreach (MTR_Admin ma in AdminInfoList)
//                {
//                    if (ma.OrgType1 == com && ma.OrgType3 == "所有部门") //具有所有部门管理权限
//                    {
//                        string conn = "Data Source=sptraining;Initial Catalog=WorkFlow;User ID=workflow;Password=workflow_2011";
//                        string strSQL = string.Format(@"select '所有部门' as ABBR,'0' as ID
//                            union all 
//                            select ABBR,ID from RUC_Organization(nolock) where IfDelete=0 and ParentID in 
//                            (select ID from RUC_Organization(nolock) where IfDelete=0 and ParentID in 
//                            (select ID from RUC_Organization(nolock) where ParentID in
//                            (select id from RUC_Organization(nolock) where ABBR='{0}' and IfDelete=0) and 
//                            IfDelete=0 and OrgTypeID=1)) or ParentID in (select ID from RUC_Organization(nolock)
//                             where ParentID in(select id from RUC_Organization(nolock) where ABBR='{0}' and IfDelete=0) and IfDelete=0 and OrgTypeID=2)
//                            ", com);
//                        DataTable dt = Worker.GetDataSet(strSQL, conn).Tables[0];
//                        dept = dt.AsEnumerable().Select(p => p[0].ToString().ToLower()).ToList();
//                        dept.Insert(0, "");
//                        return dept;
//                    }
//                    else if (ma.OrgType1 == com && ma.OrgType3 != "所有部门")//具有个别部门管理权限
//                    {
//                        dept.Add(ma.OrgType3);
//                        return dept;
//                    }
//                }
//            }
//            else if (uLevel >= 3) //系统管理员
//            {
//                string conn = "Data Source=sptraining;Initial Catalog=WorkFlow;User ID=workflow;Password=workflow_2011";
//                string strSQL = string.Format(@"select '所有部门' as ABBR,'0' as ID
//                            union all 
//                            select ABBR,ID from RUC_Organization(nolock) where IfDelete=0 and ParentID in 
//                            (select ID from RUC_Organization(nolock) where IfDelete=0 and ParentID in 
//                            (select ID from RUC_Organization(nolock) where ParentID in
//                            (select id from RUC_Organization(nolock) where ABBR='{0}' and IfDelete=0) and 
//                            IfDelete=0 and OrgTypeID=1)) or ParentID in (select ID from RUC_Organization(nolock)
//                             where ParentID in(select id from RUC_Organization(nolock) where ABBR='{0}' and IfDelete=0) and IfDelete=0 and OrgTypeID=2)
//                            ", com);
//                DataTable dt = Worker.GetDataSet(strSQL, conn).Tables[0];
//                dept = dt.AsEnumerable().Select(p => p[0].ToString().ToLower()).ToList();
//                dept.Insert(0, "");
//                return dept;
//            }
//            return dept;
//        }
        
//        protected void adminCompany_SelectedIndexChanged(object sender, EventArgs e)
//        {
//            string com = adminCompany.SelectedItem.Text;
//            List<string> dept = new List<string>();
//            if (uLevel == 2)//高级管理员
//            {
//                foreach (MTR_Admin ma in AdminInfoList)
//                {
//                    if (ma.OrgType1 == com && ma.OrgType3 == "所有部门") //具有所有部门管理权限
//                    {
//                        string conn = "Data Source=sptraining;Initial Catalog=WorkFlow;User ID=workflow;Password=workflow_2011";
//                        string strSQL = string.Format(@"select '所有部门' as ABBR,'0' as ID
//                            union all 
//                            select ABBR,ID from RUC_Organization(nolock) where IfDelete=0 and ParentID in 
//                            (select ID from RUC_Organization(nolock) where IfDelete=0 and ParentID in 
//                            (select ID from RUC_Organization(nolock) where ParentID in
//                            (select id from RUC_Organization(nolock) where ABBR='{0}' and IfDelete=0) and 
//                            IfDelete=0 and OrgTypeID=1)) or ParentID in (select ID from RUC_Organization(nolock)
//                             where ParentID in(select id from RUC_Organization(nolock) where ABBR='{0}' and IfDelete=0) and IfDelete=0 and OrgTypeID=2)
//                            ", com);
//                        adminDept.DataSource = Worker.GetDataSet(strSQL, conn);
//                        adminDept.DataTextField = "ABBR";
//                        adminDept.DataValueField = "ABBR";
//                        adminDept.DataBind();
//                        adminDept.Items.Insert(0, new ListItem("", ""));
//                        return;
//                    }
//                    else if (ma.OrgType1 == com && ma.OrgType3 != "所有部门")//具有个别部门管理权限
//                    {
//                        dept.Add(ma.OrgType3);
//                    }
//                }
//                if (adminDept.DataSource == null)
//                {
//                    adminDept.DataSource = dept;
//                    adminDept.DataBind();
//                    adminDept.Items.Insert(0, new ListItem("", ""));
//                }
//            }
//            if (uLevel >= 3) //系统管理员
//            {
//                string conn = "Data Source=sptraining;Initial Catalog=WorkFlow;User ID=workflow;Password=workflow_2011";
//                string strSQL = string.Format(@"select '所有部门' as ABBR,'0' as ID
//                            union all 
//                            select ABBR,ID from RUC_Organization(nolock) where IfDelete=0 and ParentID in 
//                            (select ID from RUC_Organization(nolock) where IfDelete=0 and ParentID in 
//                            (select ID from RUC_Organization(nolock) where ParentID in
//                            (select id from RUC_Organization(nolock) where ABBR='{0}' and IfDelete=0) and 
//                            IfDelete=0 and OrgTypeID=1)) or ParentID in (select ID from RUC_Organization(nolock)
//                             where ParentID in(select id from RUC_Organization(nolock) where ABBR='{0}' and IfDelete=0) and IfDelete=0 and OrgTypeID=2)
//                            ", com);
//                adminDept.DataSource = Worker.GetDataSet(strSQL, conn);
//                adminDept.DataTextField = "ABBR";
//                adminDept.DataValueField = "ABBR";
//                adminDept.DataBind();
//                adminDept.Items.Insert(0 ,new ListItem("",""));
//            }
//        }
//        #endregion
//        #region
//        protected void adminDept_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    string com = adminCompany.SelectedItem.Text;
        //    string dept = adminDept.SelectedItem.Text;
        //    venueType.Items.Clear();
        //    if (uLevel == 2)
        //    {
        //        foreach (MTR_Admin ma in AdminInfoList)
        //        {
        //            if (ma.OrgType1 == com && ma.OrgType3 == dept)
        //            {
        //                venueType.Items.Add(ma.VenueType);
        //            }
        //            if (ma.OrgType1 == com && ma.OrgType3 == "所有部门")
        //            {
        //                for (int i = 0; i < venueType.Items.Count; i++)
        //                {
        //                    if (venueType.Items[i].Text != ma.VenueType)
        //                    {
        //                        venueType.Items.Add(ma.VenueType);
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    if (uLevel == 3)
        //    {
        //        using (var mtr_resEn = new meetingroomManagementEntities())
        //        {
        //            var cls = (from c in mtr_resEn.MTR_bas_Type where c.available
        //                       select c.Type).Distinct();
        //            foreach(var c in cls){
        //                venueType.Items.Add(c.ToString());
        //            }
        //        }
        //    }
        //}
        #endregion

        
    }
}